Skip to content

Keep the union order in the union cache key - #818

Merged
yukinarit merged 1 commit into
yukinarit:mainfrom
youdie006:union-cache-key-order
Oct 31, 2026
Merged

yukinarit merged 1 commit into
yukinarit:mainfrom
youdie006:union-cache-key-order

Conversation

@youdie006

Copy link
Copy Markdown
Contributor

Union[int, str] == Union[str, int] (and the hashes match), so since #665 the top-level union cache returns the wrapper generated for whichever ordering was used first. The function name is still built from the actual argument order, so the other ordering misses it for the rest of the process:

from typing import Union
from serde import from_dict, to_dict

print(from_dict(Union[int, str], 1))  # 1
print(to_dict(1, c=Union[str, int]))  # serde.compat.SerdeError: 'union_se_str_int'

The same happens through from_json/to_json and for list[Union[...]] / dict[str, Union[...]] elements. This is the case #448 fixed with the old string key; #764 handled the same order-blind equality for is_opt.

This adds repr(union_cls) to UnionCacheKey. The type stays in the key, so classes that share a name are still kept apart as #665 intended. Two tests are added next to test_union_with_different_ordering: both orderings through to_json/from_json (fails on main), and same-named classes in a union (fails if the key keeps only the repr). The full test suite, black and ruff pass.

Written with AI assistance (Claude); I have reviewed the change.

typing.Union compares and hashes equal regardless of argument order, so
after yukinarit#665 UnionCacheKey returned the wrapper generated for the first
ordering seen, while the function name is built from the actual order.
Serializing or deserializing the other ordering then failed with a
KeyError/SerdeError such as 'union_se_str_int'. Add repr(union_cls) to
the key; keeping the type itself still separates same-named classes.
@yukinarit yukinarit added the bug Bug report or fix label Oct 28, 2026

@yukinarit yukinarit left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM, thanks!

@yukinarit
yukinarit merged commit 9ca6ce7 into yukinarit:main Oct 31, 2026
6 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Bug report or fix

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants